package com.googlecode.cswish.view;

import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.components.Component;

import com.googlecode.cswish.util.FreeMarkerHelper;
import com.opensymphony.xwork2.util.ValueStack;

import freemarker.core.Environment;

/**
 * @author Jerry.Feng Date: 2008-6-3
 */
public class Call extends Component {
	
	private static final Log logger = LogFactory.getLog(Call.class);
	
    public Call(ValueStack stack) {
		super(stack);
	}

    protected String name;
    
    protected String action;

    public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public boolean start(Writer writer) {
		
		
		return true;
	}
	
	public boolean end(Writer writer, String body) {
		if (action != null) {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			try {
				request.getRequestDispatcher(action).include(request, response);
			} catch (Exception ex) {
	            logger.error("can't call action:" + action, ex);
	        }
		}
		
		
		// call tag
		Object result = Mark.getExtensions(stack).get(name);
		if (result != null) {
			Environment environment = Environment.getCurrentEnvironment();
			FreeMarkerHelper.execute(environment, result, writer);
		} else {
			if (name != null) {
				logger.error("Call failed, can't find module:" + name);
			}
		}
		return false;
	}
}